package com.zg.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.spring.web.json.Json;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.UiConfiguration;

import java.util.ArrayList;

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 异常解决地址：https://cloud.tencent.com/developer/article/1849667
     */

   @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //这必须加不然服务器会报错，应为不加直接返回的是String，所以需要我们自己去转化为json格式
        if (body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }
        if (body instanceof Result){
            return body;
        }
        //过滤swagger的配置请求
        if (body instanceof UiConfiguration || body instanceof Json){
            return body;
        }
        if (body instanceof ArrayList && ((ArrayList) body).size()!=0){
           if(((ArrayList)body).get(0) instanceof SwaggerResource){
               return body;
           }
        }
        return Result.success(body);
    }
}
